#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QPlainTextEdit>
#include<QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("简单的记事本");
    QMenuBar* menbar=this->menuBar();
    QMenu* menu1=new QMenu("文件");
    menbar->addMenu(menu1);
    QAction* action1=new QAction("打开");
    QAction* action2=new QAction("保存");
    menu1->addAction(action1);
    menu1->addAction(action2);

    edit=new QPlainTextEdit(this);
    QFont font;
    font.setPixelSize(50);
    edit->setFont(font);
    this->setCentralWidget(edit);

    connect(action1,&QAction::triggered,this,&MainWindow::handle1);
    connect(action2,&QAction::triggered,this,&MainWindow::handle2);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle1()
{
    QString path=QFileDialog::getOpenFileName(this);
    QStatusBar* bar=this->statusBar();
    bar->showMessage(path);

    QFile file(path);
    bool ret=file.open(QFile::ReadOnly);
    if(!ret)
    {
        bar->showMessage(path+"打开文件失败");
    }

    QString text=file.readAll();

    file.close();

    edit->setPlainText(text);
}

void MainWindow::handle2()
{
   QString path=QFileDialog::getSaveFileName(this);
   QFile file(path);
   QStatusBar* bar=this->statusBar();
   bar->showMessage(path);
   bool ret=file.open(QFile::WriteOnly);
   if(!ret)
   {
       statusBar()->showMessage(path+"打开文件失败");
       return ;
   }
   const QString& text=edit->toPlainText();
   file.write(text.toUtf8());
   file.close();
}

